package thingapi

import (
	"iot-base/common/dbconn"
	"iot-base/common/dbobj"
	"iot-base/common/idsync"
	"iot-base/common/webapi"
	"sort"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"gorm.io/gorm"
)

func saveTS(c *gin.Context) bool {
	var ts dbobj.ThingStation
	c.ShouldBindBodyWith(&ts, binding.JSON)
	var err error
	err = onSaveThingStation(&ts)

	if err == nil {
		idsync.DirtyThing(ts.ThingID)
		webapi.SendOK(c)
	} else {
		webapi.SendError(err.Error(), webapi.DBError, c)
	}
	return true
}
func saveThingStation(ts *dbobj.ThingStation) error {
	return dbconn.DBConnection.Transaction(func(tx *gorm.DB) error {
		// 在事务中执行一些 db 操作（从这里开始，您应该使用 'tx' 而不是 'db'）

		if err := tx.Save(ts).Error; err != nil {
			return err
		}

		// 返回 nil 提交事务
		return nil
	})
}

type TsArray []dbobj.ThingStation

func (s TsArray) Len() int { return len(s) }

func (s TsArray) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

func (s TsArray) Less(i, j int) bool { return s[i].SNO < s[j].SNO }

func getTSSNO(ts *dbobj.ThingStation) {
	var tsArray TsArray
	err := dbconn.DBConnection.Table("thing_stations").
		Joins("JOIN things ON things.uid=thing_stations.thing_id and things.model_id=? and thing_stations.station_id=?",
			ts.ModelID, ts.StationID).
		//Select("thing_stations.sno,things_station.thing_id").
		Find(&tsArray).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			ts.SNO = 0
			return
		}
		return

	}
	slen := len(tsArray)
	if slen == 0 {
		ts.SNO = 0
		return
	}
	//target := 0
	sort.Sort(tsArray)
	i := 0
	isFound := false
	for i = 0; i < slen; i++ {
		if tsArray[i].ThingID == ts.ThingID {
			ts.SNO = tsArray[i].SNO
			return
		}
		if !isFound && tsArray[i].SNO != i {

			ts.SNO = i
			isFound = true

		}

	}
	if !isFound {
		ts.SNO = i
	}
}

func onSaveThingStation(ts *dbobj.ThingStation) error {
	thing := dbobj.Thing{
		UID: ts.StationID,
	}
	err := dbconn.DBConnection.First(&thing).Error
	if err != nil {
		return err
	}
	thing.UID = ts.ThingID
	err = dbconn.DBConnection.First(&thing).Error
	if err != nil {
		return err
	}
	modelID := thing.ModelID
	ts.ModelID = modelID
	if ts.SNO != 0 {
		return saveThingStation(ts)
	}
	getTSSNO(ts)
	return saveThingStation(ts)

	//return err
}
